import { defineStore } from "pinia";
import router,{constantRoutes} from "@/router";
//使用vite懒加载
const modules = import.meta.glob('../views/**/*.vue');

export const usePermissionStore = defineStore("permission", {
  state: () => ({
    menus: []
  }),

  actions: {
    generatorRouters(menus) {
      const routeList = this.filterMenusToTree(menus);
      this.menus = routeList.concat(constantRoutes);
      routeList.forEach((item) => {
        // 添加一个新的路由记录，将其作为一个已有路由的子路由
        router.addRoute(item);
      });
      
    },

    /**
     * 将扁平化菜单转为树结构
     * @param {*} menus
     */
    filterMenusToTree(menus) {
      let result = []; //存放结果的数组
      let object = {}; //临时对象
      for (const item of menus) {
        const id = item.menu_id;
        const pid = item.parent_id;
        //初始化临时对象，键为id，值为一个对象，对象中包含children属性，用于存放子路由
        if (!object[id]) {
          object[id] = {
            children: [],
          };
        }
        object[id] = {
          component: this.loadComponent(item),
          name: item.path,
          path: "/" + item.path,
          meta: {
            title: item.menu_name,
            icon: item.icon,
            affix:item.affix,
            hidden: item.menu_type == 'F' || item.visible == '1' ? true : false,  //菜单类型为F表示是按钮，不显示.visible为1表示隐藏
            order_num:item.order_num,
            menu_type:item.menu_type,  //菜单类型（M目录 C菜单 F按钮）
            link: item.is_frame ? null : item.path,
            noCache: item.is_cache ? false : true,
          },
          children: object[id]["children"],
        };
        const treeItem = object[id];
        if (pid == 0) {
          result.push(treeItem);
        } else {
          if (!object[pid]) {
            object[pid] = {
              children: [],
            };
          }
          treeItem.path = object[pid].path + treeItem.path;
          object[pid].children.push(treeItem);
        }
      }
      
      return result;
    },
    /**
     * 将路由字符串，转换为组件对象
     * @param {*} route
     */
    loadComponent(route) {
      if(route.parent_id == '0') {
        return () => import("@/layout/index.vue");
      } else if (route.component == "InnerLink") {
        return null
      } else {
        let component = modules[`../views/${route.component}.vue`]
        return component
      }
    },
  },
});
